import { History } from './base'

function ensureSlash() {
  if (window.location.hash) return
  window.location.hash = '/'
}

function getHash() {
  // '#/home'.slice(1) -> 返回值 '/home';字符串截取操作
  console.log('window.location.hash', window.location.hash)
  return window.location.hash.slice(1)
}
class HashHistory extends History {
  constructor(router) {
    super(router)
    this.router = router

    // 确保hash模式 有一个 /
    ensureSlash()
  }

  getCurrentLocation() {
    // 这里 也要拿到 hash值
    return getHash()
  }

  /// 监听hash值变化
  setupListener() {
    window.addEventListener('hashchange', () => {
      // 当hash值变化了 再次拿到hash值进行跳转
      this.transitionTo(getHash())
    })
  }
  push(location) {
    this.transitionTo(location, () => {
      // 更改hash值
      window.location.hash = location
    })
  }
}

export default HashHistory
